package com.dliyun.oap.framework.service;

import com.dliyun.oap.framework.context.OapRequestContext;
import com.dliyun.oap.framework.request.OapRequest;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;

/**
 * <pre>
 * 通过该服务方法适配器调用目标的服务方法
 * </pre>
 *
 * @author stjdydayou
 * @version 1.0
 */
@Slf4j
public class ServiceMethodAdapter {

    /**
     * 调用OAP服务方法
     *
     * @param request
     * @return
     */
    public Object invokeServiceMethod(OapRequest request) {
        try {
            OapRequestContext requestContext = request.getRequestContext();
            // 分析上下文中的错误
            ServiceMethodHandler serviceMethodHandler = requestContext.getServiceMethodHandler();
            if (log.isDebugEnabled()) {
                log.debug("执行" + serviceMethodHandler.getHandler().getClass() + "." + serviceMethodHandler.getHandlerMethod().getName());
            }
            if (serviceMethodHandler.isHandlerMethodWithParameter()) {
                return serviceMethodHandler.getHandlerMethod().invoke(serviceMethodHandler.getHandler(), request);
            } else {
                return serviceMethodHandler.getHandlerMethod().invoke(serviceMethodHandler.getHandler());
            }
        } catch (Throwable e) {
            if (e instanceof InvocationTargetException) {
                InvocationTargetException inve = (InvocationTargetException) e;
                throw new RuntimeException(inve.getTargetException());
            } else {
                throw new RuntimeException(e);
            }
        }
    }

}
